package com.company.test.sync;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author zhangyan
 * @version $ Id: RWDemo3.java, v 0.1 2020/9/4 11:36 zhangyan Exp $
 */
public class RWDemo3 {
    static ReentrantReadWriteLock lock = new ReentrantReadWriteLock(false);
    static volatile int a = 0;

    public static void main(String[] args) {
        Thread t1 = new Thread(() -> {
            ReentrantReadWriteLock.ReadLock readLock = lock.readLock();
            readLock.lock();
            try {
                TimeUnit.DAYS.sleep(1);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                readLock.unlock();
                System.out.println("t1释放锁成功");
            }
        }, "第一个");
        t1.start();

        System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (Exception e) {
            e.printStackTrace();
        }

        Thread t2 = new Thread(() -> {
            ReentrantReadWriteLock.WriteLock writeLock = lock.writeLock();
            writeLock.lock();
            System.out.println("*********************" + a);
            try {
//                TimeUnit.DAYS.sleep(1);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                writeLock.unlock();

            }
        }, "第二个");
        t2.start();


    }
}
